import React, { useState } from "react";
import {
  Card,
  Table,
  Button,
  Space,
  Modal,
  Form,
  Input,
  Tree,
  message,
  Popconfirm,
} from "antd";
import {
  PlusOutlined,
  EditOutlined,
  DeleteOutlined,
  SettingOutlined,
} from "@ant-design/icons";
import { useNavigate } from "react-router-dom";

interface Role {
  id: number;
  name: string;
  code: string;
  description: string;
  permissions: string[];
}

const Role: React.FC = () => {
  const navigate = useNavigate();
  const [form] = Form.useForm();
  const [modalVisible, setModalVisible] = useState(false);
  const [editingRole, setEditingRole] = useState<Role | null>(null);
  const [roles, setRoles] = useState<Role[]>([
    {
      id: 1,
      name: "超级管理员",
      code: "SUPER_ADMIN",
      description: "系统超级管理员",
      permissions: ["*"],
    },
    {
      id: 2,
      name: "普通用户",
      code: "USER",
      description: "普通用户",
      permissions: ["view:profile", "edit:profile"],
    },
  ]);

  // 权限树数据
  const permissionTree = [
    {
      title: "系统管理",
      key: "system",
      children: [
        {
          title: "用户管理",
          key: "user",
          children: [
            { title: "查看用户", key: "view:user" },
            { title: "创建用户", key: "create:user" },
            { title: "编辑用户", key: "edit:user" },
            { title: "删除用户", key: "delete:user" },
          ],
        },
        {
          title: "角色管理",
          key: "role",
          children: [
            { title: "查看角色", key: "view:role" },
            { title: "创建角色", key: "create:role" },
            { title: "编辑角色", key: "edit:role" },
            { title: "删除角色", key: "delete:role" },
          ],
        },
      ],
    },
    {
      title: "个人中心",
      key: "profile",
      children: [
        { title: "查看个人信息", key: "view:profile" },
        { title: "编辑个人信息", key: "edit:profile" },
      ],
    },
  ];

  const columns = [
    {
      title: "角色名称",
      dataIndex: "name",
      key: "name",
    },
    {
      title: "角色编码",
      dataIndex: "code",
      key: "code",
    },
    {
      title: "描述",
      dataIndex: "description",
      key: "description",
    },
    {
      title: "操作",
      key: "action",
      render: (_: unknown, record: Role) => (
        <Space size="middle">
          <Button
            type="primary"
            icon={<EditOutlined />}
            onClick={() => handleEdit(record)}
          >
            编辑
          </Button>
          <Button
            type="default"
            icon={<SettingOutlined />}
            onClick={() => navigate("/role-permission")}
          >
            权限配置
          </Button>
          <Popconfirm
            title="确定要删除这个角色吗？"
            onConfirm={() => handleDelete(record.id)}
          >
            <Button danger icon={<DeleteOutlined />}>
              删除
            </Button>
          </Popconfirm>
        </Space>
      ),
    },
  ];

  const handleAdd = () => {
    setEditingRole(null);
    form.resetFields();
    setModalVisible(true);
  };

  const handleEdit = (role: Role) => {
    setEditingRole(role);
    form.setFieldsValue({
      ...role,
      permissions: role.permissions,
    });
    setModalVisible(true);
  };

  const handleDelete = (id: number) => {
    setRoles(roles.filter((role) => role.id !== id));
    message.success("删除成功");
  };

  const handleModalOk = () => {
    form.validateFields().then((values) => {
      if (editingRole) {
        // 编辑现有角色
        setRoles(
          roles.map((role) =>
            role.id === editingRole.id ? { ...role, ...values } : role
          )
        );
        message.success("更新成功");
      } else {
        // 添加新角色
        const newRole = {
          id: roles.length + 1,
          ...values,
        };
        setRoles([...roles, newRole]);
        message.success("添加成功");
      }
      setModalVisible(false);
    });
  };

  return (
    <Card
      title="角色管理"
      extra={
        <Button type="primary" icon={<PlusOutlined />} onClick={handleAdd}>
          添加角色
        </Button>
      }
    >
      <Table columns={columns} dataSource={roles} rowKey="id" />
      <Modal
        title={editingRole ? "编辑角色" : "添加角色"}
        open={modalVisible}
        onOk={handleModalOk}
        onCancel={() => setModalVisible(false)}
        width={600}
      >
        <Form form={form} layout="vertical">
          <Form.Item
            name="name"
            label="角色名称"
            rules={[{ required: true, message: "请输入角色名称" }]}
          >
            <Input placeholder="请输入角色名称" />
          </Form.Item>
          <Form.Item
            name="code"
            label="角色编码"
            rules={[{ required: true, message: "请输入角色编码" }]}
          >
            <Input placeholder="请输入角色编码" />
          </Form.Item>
          <Form.Item name="description" label="描述">
            <Input.TextArea placeholder="请输入角色描述" />
          </Form.Item>
          <Form.Item name="permissions" label="权限">
            <Tree
              checkable
              defaultExpandAll
              treeData={permissionTree}
              fieldNames={{
                title: "title",
                key: "key",
                children: "children",
              }}
            />
          </Form.Item>
        </Form>
      </Modal>
    </Card>
  );
};

export default Role;
